package com.baidu.iit.pxp.parser;

import com.baidu.iit.pxp.constants.BpmnXMLConstants;
import com.baidu.iit.pxp.converter.BaseChildElementParser;
import com.baidu.iit.pxp.model.ActivitiListener;
import com.baidu.iit.pxp.model.BaseElement;
import com.baidu.iit.pxp.model.BpmnModel;
import com.baidu.iit.pxp.model.FieldExtension;
import com.baidu.iit.pxp.util.BpmnXMLUtil;
import org.apache.commons.lang3.StringUtils;

import javax.xml.stream.XMLStreamReader;

/**
 * User: huangweili
 * Date: 14-4-26
 * Time: 下午3:53
 */
public class FieldExtensionParser extends BaseChildElementParser {

    public String getElementName() {
        return BpmnXMLConstants.ELEMENT_FIELD;
    }

    public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception {

        if (parentElement instanceof ActivitiListener == false) return;

        FieldExtension extension = new FieldExtension();
        BpmnXMLUtil.addXMLLocation(extension, xtr);
        extension.setFieldName(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_FIELD_NAME));

        if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_FIELD_STRING))) {
            extension.setStringValue(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_FIELD_STRING));

        } else if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_FIELD_EXPRESSION))) {
            extension.setExpression(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_FIELD_EXPRESSION));

        } else {
            boolean readyWithFieldExtension = false;
            try {
                while (readyWithFieldExtension == false && xtr.hasNext()) {
                    xtr.next();
                    if (xtr.isStartElement() && BpmnXMLConstants.ELEMENT_FIELD_STRING.equalsIgnoreCase(xtr.getLocalName())) {
                        extension.setStringValue(xtr.getElementText().trim());

                    } else if (xtr.isStartElement() && BpmnXMLConstants.ATTRIBUTE_FIELD_EXPRESSION.equalsIgnoreCase(xtr.getLocalName())) {
                        extension.setExpression(xtr.getElementText().trim());

                    } else if (xtr.isEndElement() && getElementName().equalsIgnoreCase(xtr.getLocalName())) {
                        readyWithFieldExtension = true;
                    }
                }
            } catch (Exception e) {
                LOGGER.warn("Error parsing field extension child elements", e);
            }
        }

        if (parentElement instanceof ActivitiListener) {
            ((ActivitiListener) parentElement).getFieldExtensions().add(extension);
        }
    }
}
